import React, { lazy, useEffect } from "react";
import { useRoutes, useLocation, useNavigate } from "react-router-dom"
import { message } from 'antd';
// 重定向
import { Navigate } from "react-router-dom";
import {
  DesktopOutlined,
  FileOutlined
} from '@ant-design/icons';

const Login = lazy(() => import("@/views/Login"));
const Home = lazy(() => import("@/views/Home"));
const About = lazy(() => import("@/views/About"));
const About2 = lazy(() => import("@/views/About/2"));

const widthLoadingComponent = (comp: JSX.Element) => (
  <React.Suspense fallback={<div>Loading...</div>}>{comp}</React.Suspense>
)


const routes = [
  {
    path: "/",
    element: <Navigate to="/home" />,
  },
  {
    path: "/login",
    key: "login",
    meta: {
      label: "登陆",
      show: false
    },
    element: widthLoadingComponent(<Login />),
  },
  {
    path: "/home",
    key: "home",
    meta: {
      label: "首页",
      icon: <DesktopOutlined/>,
    },
    element: widthLoadingComponent(<Home />),
  },
  {
    path: "/about",
    key: "about",
    meta: {
      label: "关于",
      icon: <FileOutlined/>,
    },
    // element: widthLoadingComponent(<About />),
    children: [
      {
        path: "/about/2",
        key: "about/2",
        meta: {
          label: "关于-id"
        },
        element: widthLoadingComponent(<About2/>),
      },
    ]
  }
]

// 去往登录页
const ToLogin = () => {
  const navigateTo = useNavigate()
  // 加载完这个组件之后实现跳转
  useEffect(() => {
    // 加载完组件之后执行这里的代码
    navigateTo("/login");
    message.warning("您还没有登录，请登录后再访问！");
  }, [])
  return <div></div>
}

// 去往首页
const ToHome = () => {
  const navigateTo = useNavigate()
  // 加载完这个组件之后实现跳转
  useEffect(() => {
    // 加载完组件之后执行这里的代码
    navigateTo("/home");
    message.warning("您已经登录过了！");
  }, [])
  return <div></div>
}

// 手写封装路由守卫
const BeforeRouterEnter = () => {
  const outlet = useRoutes(routes);
  const location = useLocation()
  let token = localStorage.getItem("lege-react-management-token");
  // 如果访问的是登录页面， 并且有token， 跳转到首页
  if (location.pathname === "/login" && token) {
    // 这里不能直接用 useNavigate 来实现跳转 ，因为需要BeforeRouterEnter是一个正常的JSX组件
    return <ToHome />
  }
  // 如果访问的不是登录页面，并且没有token， 跳转到登录页
  if (location.pathname !== "/login" && !token) {
    return <ToLogin />
  }
  return outlet
}

export { routes, BeforeRouterEnter };